<?php
namespace app\client\controller;
use app\common\lib\Redis;

class Qrcode extends Base {
    public function __construct() {
        parent::__construct();
    }
    
    private function _send($scene) {
        $redis = new Redis();
        $ACCESS_TOKEN = $redis->get('wx_access_token');
        $redis->close();
        if(empty($ACCESS_TOKEN)) {
            return errorResult();
        }
        
        $ch = curl_init('https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=' . $ACCESS_TOKEN);
        curl_setopt($ch, CURLOPT_POST, 1); //设置为POST方式
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(['scene' => $scene, 'width' => 280, 'is_hyaline' => true]));//POST数据
        $result = curl_exec($ch);
        curl_close($ch);
        if(empty($result)) {
            return errorResult();
        }
        if(stripos($result, '{') === 0) {
            return errorResult();
        }
        
        return $result;
    }
    
    
    public function invite() {
        $scene = '?f=i&iv=' . $this->userid . '&fi=' . $this->userid;
        
        return $this->_send($scene);
    }
    
    public function chat() {
        $chatId = request()->get('chatId', 0, 'intval');
        $scene = '?f=g&ci=' . $chatId;
        
        $chat = model('Chat')->findOne(['chat_id' => $chatId], ['chat_type']);
        if(empty($chat)) {
            return errorResult('dddd');
            
            if($chat['chat_type'] == 4) {
                $scene .= ('&d=s&s=' . $this->userid);
            }
        }
        
        $scene .= '&fi=' . $this->userid;
        
        return $this->_send($scene);
    }
    
    public function store() {
        $storeId = request()->get('storeId', 0, 'intval');
        $scene = '?f=s&si=' . $storeId;
        $scene .= '&fi=' . $this->userid;
        
        return $this->_send($scene);
    }
    
    
    public function invite1() {
        $scene = '?from=invite&inviter=' . $this->userid . '&fromUserId=' . $this->userid;

        return $this->_send($scene);
    }
    
    public function chat1() {
        $chatId = request()->get('chatId', 0, 'intval');
        $scene = '?from=goods&chatId=' . $chatId;
        
        $chat = model('Chat')->findOne(['chat_id' => $chatId], ['chat_type']);
        if(empty($chat)) {
            return errorResult();
            
            if($chat['chat_type'] == 4) {
                $scene .= ('&dst=share&sharer=' . $this->userid);
            }
        }
        
        $scene .= '&fromUserId=' . $this->userid;
       
        return $this->_send($scene);
    }
    
}